package com.song.tools.songtest.config;

import cn.dev33.satoken.exception.NotPermissionException;
import cn.dev33.satoken.exception.NotRoleException;
import com.song.tools.core.beans.response.ResultVo;
import com.song.tools.core.exception.BusinessException;
import com.song.tools.core.exception.ExceptionCodeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import static org.springframework.http.HttpStatus.OK;

/**
 * 全局异常处理
 *
 * @author song tools
 * @since 2024-06-21
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    /**
     * sa-toke权限校验
     */
    @ExceptionHandler(NotPermissionException.class)
    @ResponseStatus(OK)
    public ResultVo<Boolean> handleNotPermissionException(NotPermissionException exception) {
        log.error("NotPermissionException occurred ! ", exception);
        return ResultVo.error(ExceptionCodeEnum.USER_NOT_AUTHORIZED.getCode(), exception.getMessage());
    }

    /**
     * sa-toke角色校验
     */
    @ExceptionHandler(NotRoleException.class)
    @ResponseStatus(OK)
    public ResultVo<Boolean> handleNotRoleException(NotRoleException exception) {
        log.error("NotRoleException occurred ! ", exception);
        return ResultVo.error(ExceptionCodeEnum.USER_ROLE_ERROR.getCode(), exception.getMessage());
    }

    /**
     * 业务异常
     *
     * @param exception 业务异常
     * @return 响应
     */
    @ResponseStatus(OK)
    @ExceptionHandler(BusinessException.class)
    public ResultVo<Boolean> handleCustomException(BusinessException exception) {
        log.error("业务异常：{}", exception.getMessage());
        return ResultVo.error(exception.getCode(), exception.getMessage());
    }

    /**
     * 全局异常
     *
     * @param exception 全局异常
     * @return 响应
     */
    @ResponseStatus(OK)
    @ExceptionHandler(Exception.class)
    public ResultVo<Boolean> handleException(Exception exception) {
        log.error("未知异常：{}", exception.getMessage());
        return ResultVo.error(ExceptionCodeEnum.UNKNOWN_ERROR.getCode(), exception.getMessage());
    }
}
